package com.sky.interceptor;

import com.sky.context.ThreadLocalUtil;
import com.sky.properties.JwtProperties;
import com.sky.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class UserLoginInterceptor implements HandlerInterceptor {

    @Autowired
    JwtProperties jwtProperties;
    /**
     * 在访问controller方法之前拦截
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //1. 前端会把token放在请求头中传递给后台
        //2. 拦截器从请求头中获取token
        String token = request.getHeader(jwtProperties.getUserTokenName());
        //3. 解析token获取员工Id
        try {
            Claims claims = JwtUtil.parseJWT(jwtProperties.getUserSecret(), token);
            Long userId = Long.valueOf(claims.get("userId").toString());
            //把empId和当前线程绑定
            ThreadLocalUtil.setCurrentId(userId);
            System.out.println("[拦截器]当前线程名称："+Thread.currentThread().getName());
            //4. 能正常解析token，说明已经登录，放行
            return true;
        } catch (Exception e) {
            //5. 如果出现异常，说明token被篡改，返回401认证错误状态码，不放行
            response.setStatus(401);
        }
        StringBuffer url = request.getRequestURL();
        log.error("未登录，非法请求：{}",url);
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //移除线程上绑定的empId
        ThreadLocalUtil.removeCurrentId();
    }
}
